package com.example.datn.fragments;


import java.util.ArrayList;

import com.example.datn.R;
import com.example.datn.activities.PlayAlbumMediaActivity;
import com.example.datn.adapter.AlbumItemAdapter;
import com.example.datn.manager.AlbumManager;
import com.example.datn.manager.ResourceManager;
import com.example.datn.manager.SongManager;
import com.example.datn.objects.AlbumObject;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;

public class AlbumFragment extends Fragment {

	private TextView tv_status_connection;
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {			
		
		View rootView = inflater.inflate(R.layout.list_albums, container, false);
		tv_status_connection = (TextView)rootView.findViewById(R.id.tv_status_connect_listsong);
		
		if(!ResourceManager.hasConnection)
			tv_status_connection.setVisibility(View.VISIBLE);
		else
			tv_status_connection.setVisibility(View.GONE);
		
		GridView gridAlbum = (GridView) rootView.findViewById(R.id.grid_list_album);
		ArrayList<AlbumObject> listAllAbum = AlbumManager.getInstance()
				.getListAlbum();

		AlbumItemAdapter myAdapter = new AlbumItemAdapter(getActivity(),
				R.layout.my_album_item, listAllAbum);
		
		for (AlbumObject album : listAllAbum) {
			album.setAlbumAdapter(myAdapter);
			if(album.getBitmapImage() == null)
				album.loadImage(myAdapter);
		}

		gridAlbum.setAdapter(myAdapter);
		gridAlbum.setOnItemClickListener(AlbumItemClickListener);
		
		return rootView;
	}

	OnItemClickListener AlbumItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int id,
				long arg3) {
			//-------------------
			MediaPlayer media = SongManager.getInstance().getCurrentMediaPlayer();
			if(media != null){
				if(media.isPlaying())
					media.reset();
				media.release();
			}
			AlbumObject album = AlbumManager.getInstance().getListAlbum().get(id);
			AlbumManager.getInstance().setCurrentAlbum(album);			
			Intent i = new Intent(getActivity(), PlayAlbumMediaActivity.class);
			startActivity(i);
		}
	};
}
